//
//  AppDelegate.swift
//  01- 搭建框架
//
//  Created by as888 on 15/10/14.
//  Copyright © 2015年 任伟. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        setupAppearance()
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        window?.backgroundColor = UIColor.whiteColor()
        
        window?.rootViewController = defaultRootViewController
        
        window?.makeKeyAndVisible()
        
        print(UserAccountViewModel.sharedUserAccount.account)
        
        print(isNewVersion)
        
        // 注册通知
        NSNotificationCenter.defaultCenter().addObserverForName(WBSwitchRootViewControllerNotification,
            object: nil,
            queue: nil)
            { [weak self] (notification) -> Void in
                print(NSThread.currentThread())
                print(notification)
                
                //切换控制器
                self?.window?.rootViewController = MainViewController()
        }
        
        SQLiteManager.sharedManager
        
        return true
    }
    
    // 注销通知
    deinit {
        
        NSNotificationCenter.defaultCenter().removeObserver(self,
            name: WBSwitchRootViewControllerNotification,
            object: nil)
    }
    
    // 设置全局外观
    private func setupAppearance() {
        UINavigationBar.appearance().tintColor = WBAppearanceTintColor
        UITabBar.appearance().tintColor = WBAppearanceTintColor
    }
}

/// MAKE: -界面切换代码
extension AppDelegate {
    ///启动的根视图控制器
    private var defaultRootViewController: UIViewController {
    
        // 判断是否登录
        if UserAccountViewModel.sharedUserAccount.userLogon{
            return isNewVersion ? NewFeatrueViewController() : WelcomeViewController()
        }
        
        // 如果没有登录返回主控制器
        return MainViewController()
    }
    
    /// 判断是否新版本
    private var isNewVersion: Bool {
        
        // 当前版本
        //print(NSBundle.mainBundle().infoDictionary)
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
        let version = Double(currentVersion)!
        print("当前版本 \(version)")
        
        // 之前的版本
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        print("之前的版本\(sandboxVersion)")
        
        
        //保存当前的版本
        NSUserDefaults.standardUserDefaults().setDouble(version, forKey: sandboxVersionKey)
        return version > sandboxVersion
    }
}
